#ifndef  _SPEED_H_
#define  _SPEED_H_

#include "../define/define.h"
#include "../util/lock.h"

struct data 
{
	uint32 bytes;
	uint32 tick;
};

#define max_bytes  1024

class  speed
{
public:

	speed()
	{
		func_lock locker;
		reset();
	}

	~speed()
	{
	}
	
	void  addbyte(uint32 bytes, uint32 tick)
	{
		func_lock locker;
		if(bytes == 0)
			return;
          
		if(m_pos > max_bytes)
			m_pos = 0;

	     m_data[m_pos].bytes = bytes;
	     m_data[m_pos].tick = tick;
		 m_last_tick = tick;
		 m_pos = m_pos + 1;
         cale(tick);
	}

	void  cale(uint32 tick)
	{
		func_lock locker;
		if(tick - 500 < m_last_tick)
			return;

		float new_speed = 0.0f;
		bool  null_value = true;
		uint32 min_tick = 0xffffffff;
		for(int i =0; i<max_bytes; i++)
		{
			if(m_data[i].bytes > 0 && m_data[i].tick >= tick - 1000)
				null_value = false;

            if(m_data[i].tick > tick - 1000)
			{
				new_speed = new_speed + m_data[i].bytes;

				if(m_data[i].tick < min_tick)
					min_tick = m_data[i].tick;
			}
		}

		if (null_value == true)
		{
			m_speed = 0.75f * m_speed;
		    return;
		}

		if(tick - min_tick > 1000)
			m_speed = 0.75f * m_speed + 0.25f * (new_speed * 1000 / (float)(tick - min_tick)) / 1024.0f; 
	    
		if(tick - min_tick < 1000)
			m_speed = 0.75f * m_speed + 0.25f * new_speed / 1024.0f;
	}
	
	float get_speed()
	{
		return m_speed;
	}

	bool  reset()
	{
		func_lock locker;
		m_speed = 0.0f;
		m_last_tick = 0;
		m_active = false;
        m_pos    = 0;
		memset(m_data, 0,sizeof(data) * max_bytes);
	}

private:
   
	float  m_speed;
	uint32 m_last_tick;
    
	bool   m_active;
	uint8  m_pos;
	
    data   m_data[max_bytes];
};

#endif